package org.vectrics.recruiter.struts.admin.job.candidate;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.mail.struts.BulkEmailForm;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobCandidate;
import org.vectrics.recruiter.job.JobCandidateCriteria;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;


public class JobCandidatesEmailAction extends VectricsStrutsAction {
    private static Category log = Category.getInstance(JobCandidatesEmailAction.class);

	/**
	 *Find candidates and pass them as recipients to bulk emailer
	 */
	public String doExecute(VectricsActionData actionData)	throws JspException {
		Request request = actionData.getRequest();
		String forward = "success";		 	
		
		BulkEmailForm form = new BulkEmailForm();
		form.setFromEmail(actionData.getAuthPerson().getContactInfo().getEmail());
		form.setFromName(actionData.getAuthPerson().getName());
		actionData.setForm(form);
		
		String jobIdParam = request.getParameter("jobId");
		Long jobId = new Long(jobIdParam);
		Job job = RecruitServiceLocator.getJobProvider().findJob(jobId);
		if (job != null) {
			JobCandidateCriteria criteria = new JobCandidateCriteria();
			criteria.setJob(job);
			Collection candidates = RecruitServiceLocator.getJobProvider().findJobCandidates(criteria, 0, 10000);
			Iterator iter = candidates.iterator();
			while (iter.hasNext()) {
				JobCandidate jobCandidate = (JobCandidate)iter.next();
				Person person = jobCandidate.getCandidate().getPerson();
				String attributeName = "recip_" + person.getId();
				request.setAttribute(attributeName, person.getName());
				log.info("Adding candidate to email list: " + person);
			}
		} else {
			throw new SystemException("Job is null for id: " + jobId);
		}
		
		return (forward);
	}

		
}
